<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/17
 * Time: 14:08
 */

namespace app\home\controller;

use \think\Controller;

class Common extends Controller
{
    protected function _initialize()
    {
        $controller = request()->controller();
        $action = request()->action();
        $route = strtolower($controller . "." . $action);
        //添加忽略登录校验请求
//        if (in_array($route, ['index.login', 'index.register', 'index.forget', 'index.getvcode', 'upload.index', 'index.app_register'])) {
//
//        } else {
//            if (!session("user_id")) {
//                //用户未登录
//                $this->redirect('Index/login');
//            }
//        }
        //判断cookie值
        if(cookie("user_id")){
            session("user_id", cookie("user_id"));
        }

        //添加登录校验请求
        if (in_array($route, ['notice.index', 'notice.detail', 'user.sign', 'cart.addcart'])) {
            if (!session("user_id")) {
                if(request()->isAjax()){
                    header("content-type:application/json");
                    exit(json_encode(["result_code"=>1111, "result_info"=>"用户未登录", "result_data"=>[]]));
                }else{
                    //用户未登录
                    $this->redirect('Index/login');
                }
            }
        }
        $this->assign("route", $route);
    }

    /**
     * ajax成功信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxSuccess($info = "", $extra = array())
    {
        header("content-type:application/json");
        $result = array(
            "result_code" => 0,
            "result_info" => $info,
            "result_data" => $extra,
        );
        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * ajax失败信息
     *
     * @param string $info 信息内容
     * @param array $extra 额外数据
     */
    protected function ajaxError($info = "", $extra = array())
    {
        header("content-type:application/json");
        $result = array(
            "result_code" => 2222,
            "result_info" => $info,
            "result_data" => $extra,
        );

        die(json_encode($result, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 设置页面标题
     */
    protected function templateTitle($title)
    {
        $this->assign("templateTitle", $title);
    }

}